import { FrontStoreStocksService } from './services/frontStoreStocksService';
import { InnerMessageHandleManager } from './common/fnc/innerMessgeHandle';
import { FNCManager } from './common/fnc/fncManager';
import { PagingMessage } from './components/scrollable/y-scrollable-container';
import { InitializationService } from './pages/initialization/index';
import { PrividerService } from './pages/initialization/prividerService';
import { BaseComponent } from './components/baseComponent';
import { AppComponents } from './components/app-components/app-components';
import { CommonComponents } from './components/common-components/common-components';
import { businsessHttpServer } from './common/http/http-server';
import { MessageBoxService } from './components/messageBox/messageBoxService';
import { LocalstorageDataManage } from './common/localstoreage/localstoreageDataManage';
import { TimeManager } from './common/timeManager';
import { ExpeditionOrderMessageHandle, SoldOutMessageHandle } from './common/fnc/messageHandle';
import { Subscription, Observable,BehaviorSubject } from 'rxjs';
import { SeedDataManage } from './../assets/mock-data/seed';
import { ChangeDetectorRef, ViewChild, ElementRef } from "@angular/core";
import { ConfirmMessageResult } from './components/messageBox/confirmMessage';
import { BaseAppComponent, SidenavOption } from './app.component';

import {
	Component,
	OnInit,
	ViewEncapsulation
} from '@angular/core';
import { Router } from "@angular/router";
import { NavigateManage } from "./common/navigateManage";
import { throttle } from "./common/utils/extended";



export class AppStateService{
	title$ = new BehaviorSubject<string>("");
    pagingInfo$ = new BehaviorSubject<PagingMessage>({previousCount:0,nextCount:0,turningPage:()=>{
        console.log("init pagingInfo$");
    }});

    changeTitle(title){
        this.title$.next(title);
    }

    changePagingInfo(pagingInfo:PagingMessage){
        this.pagingInfo$.next(pagingInfo);
    }

    getTitle$(){
        return this.title$.share();
    }

    getPagingInfo$(){
        return this.pagingInfo$.share();
    }
}


@Component({
	selector: 'app',
	encapsulation: ViewEncapsulation.None,
	styleUrls: [
		'./app.component.scss'
	],
	template: `
      <div class="app-delivery-container">
          <base-app [sidenavOptions]="sidenavOptions">
              <div fxLayout="row" fxFlex="100%" style="line-height:1;">
                <span fxLayout="row" fxLayoutAlign="space-between" fxFlex="55%">
                  <span class="solution-title nav-item color-white text-l" fxLayoutAlign="start center" routerLink="/chefHome">{{title$ | async}}</span>
                  <span class="w160 text-l color-white" fxLayoutAlign="center center">{{baseAppComponent.currentAt$ | async}}</span>
                </span>
                <span class="nav-item w160 color-white text-l" fxLayoutAlign="center center" fxFlex="15%" routerLink="/chefScrap" routerLinkActive="active">报废</span>
                <button class="nav-item w160 color-white text-l" fxLayoutAlign="center center" fxFlex="15%"  (click)="pagingInfo && pagingInfo.turningPage(-1)"><i class="material-icons">expand_less</i>{{pagingInfo && pagingInfo.previousCount == 0 ? '' : pagingInfo&&pagingInfo.previousCount}}</button>
                <button class="nav-item w160 color-white text-l" fxLayoutAlign="center center" fxFlex="15%"  (click)="pagingInfo && pagingInfo.turningPage(1)"><i class="material-icons">expand_more</i>{{pagingInfo && pagingInfo.nextCount == 0 ? '' : pagingInfo&&pagingInfo.nextCount}}</button>
              </div>
          </base-app>
      </div>
  `
})
export class appCustomerComponent extends BaseComponent implements OnInit {
	@ViewChild(BaseAppComponent)
	private baseAppComponent: BaseAppComponent;

	title$ = this.appStateService.getTitle$();

	sidenavOptions: Array<SidenavOption> = [
		{
			routerLink: "/chefDisplay",
			class: "iconfont icon-setting",
			title: "制作方案"
		},
		{
			routerLink: "/chefReset",
			class: "iconfont icon-reset",
			title: "重置终端"
		}
	]
	constructor(
		private appStateService:AppStateService,
		private frontStoreStocksService: FrontStoreStocksService,
	) {
		super();
	}

    pagingInfo: PagingMessage

	async refresh(){
		try {
			let localSolution = LocalstorageDataManage.current.getValidSolution();
			if(!localSolution) return;
			const kitchenSolutions = await this.frontStoreStocksService.getChefKitchenSolutions();
			let validSolution = kitchenSolutions.find(x=>x.id == (localSolution && localSolution.id));
			LocalstorageDataManage.current.setValidSolution(validSolution || {});	
			this.appStateService.changeTitle(LocalstorageDataManage.current.getValidSolution() && LocalstorageDataManage.current.getValidSolution().name);
		} catch (error) {
			console.error(error)
		}
	}

	public async ngOnInit() {
		this.baseAppComponent.onInitializationServiceComplete = () => {
			PrividerService.current.navigate(InitializationService.current.getPathByComponentName("bindChef"));
		}

		this.appStateService.getPagingInfo$().subscribe((pagingInfo)=>{
			this.pagingInfo = pagingInfo;
		})


	}

	async ngAfterViewInit() {
		const host = LocalstorageDataManage.current.getLDCConfig() && LocalstorageDataManage.current.getLDCConfig().host;    
		if (host) {
			await FNCManager.Current.Connect(host);
			FNCManager.Current.FNC.RegistMessageHandler("innerMessage", (message) => {
				InnerMessageHandleManager.Current.ReceivedMessage(message);
			})
		}

		InnerMessageHandleManager.Current.RegistMessageHandle();
		const soldOutMessageHandle = InnerMessageHandleManager.Current.GetMessageHanle<SoldOutMessageHandle>("SoldOutMessageHandle");
		soldOutMessageHandle.OnMessage = async (soldOuts) => {
			this.frontStoreStocksService.changeEntities(<any>soldOuts);
		}
		this.frontStoreStocksService.initErrorHandler = throttle((error)=>{
			console.error(error)
		}, 6000)

		this.refresh();
	}
}



